<template>
  <div class="work-order-create page-container">
    <div class="page-header">
      <h2>创建工单</h2>
      <div>
        <el-button type="primary" @click="openImportDialog">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button @click="$router.back()">返回</el-button>
      </div>
    </div>

    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <!-- 基础字段 -->
        <div v-if="basicFields.length > 0">
          <el-divider content-position="left">基础字段</el-divider>
          <el-row :gutter="20">
            <template v-for="field in visibleBasicFields" :key="field.name">
              <el-col :span="12" v-if="field.field_type !== 'textarea'">
                <!-- 文本字段 -->
                <el-form-item v-if="field.field_type === 'text'" :label="field.label" :prop="field.name">
                  <el-input 
                    v-model="form[field.name]"
                    :placeholder="field.name === 'work_order_number' ? '系统自动生成' : (field.placeholder || `请输入${field.label}`)"
                    :readonly="field.name === 'work_order_number'"
                    :disabled="field.name === 'work_order_number'"
                  />
                </el-form-item>
                
                <!-- 选择字段 -->
                <el-form-item v-else-if="field.field_type === 'select'" :label="field.label" :prop="field.name">
                  <el-select 
                    v-model="form[field.name]"
                    :placeholder="field.placeholder || `请选择${field.label}`"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="option in getFieldOptions(field)"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    />
                  </el-select>
                </el-form-item>
                
                <!-- 日期时间字段 -->
                <el-form-item v-else-if="field.field_type === 'datetime'" :label="field.label" :prop="field.name">
                  <el-date-picker
                    v-model="form[field.name]"
                    type="datetime"
                    :placeholder="field.placeholder || `请选择${field.label}`"
                    format="YYYY/MM/DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              
              <!-- 文本域字段（占满一行） -->
              <el-col :span="24" v-if="field.field_type === 'textarea'">
                <el-form-item :label="field.label" :prop="field.name">
                  <el-input
                    v-model="form[field.name]"
                    type="textarea"
                    :rows="3"
                    :placeholder="field.placeholder || `请输入${field.label}`"
                  />
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </div>



        <!-- 自定义字段 -->
        <div v-if="customFields.length > 0">
          <el-divider content-position="left">自定义字段</el-divider>
          <div v-for="field in customFields" :key="field.id">
            <!-- 文本字段 -->
            <el-form-item v-if="field.field_type === 'text'" :label="field.label || field.name">
              <el-input 
                v-model="customFieldValues[field.name]"
                :placeholder="`请输入${field.label || field.name}`"
              />
            </el-form-item>
            
            <!-- 单选字段 -->
            <el-form-item v-else-if="field.field_type === 'select'" :label="field.label || field.name">
              <el-select 
                v-model="customFieldValues[field.name]"
                :placeholder="`请选择${field.label || field.name}`"
                style="width: 100%"
              >
                <el-option
                  v-for="option in getCustomFieldOptions(field)"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
            
            <!-- 多选字段 -->
            <el-form-item v-else-if="field.field_type === 'checkbox'" :label="field.label || field.name">
              <el-checkbox-group v-model="customFieldValues[field.name]">
                <el-checkbox
                  v-for="option in getCustomFieldOptions(field)"
                  :key="option.value"
                  :label="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <!-- 列表字段 -->
            <el-form-item v-else-if="field.field_type === 'list'" :label="field.label || field.name">
              <el-select 
                v-model="customFieldValues[field.name]"
                :placeholder="`请选择${field.label || field.name}`"
                style="width: 100%"
              >
                <el-option
                  v-for="option in getCustomFieldOptions(field)"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
            
            <!-- 日期时间字段 -->
            <el-form-item v-else-if="field.field_type === 'datetime'" :label="field.label || field.name">
              <el-date-picker
                v-model="customFieldValues[field.name]"
                type="datetime"
                :placeholder="`请选择${field.label || field.name}`"
                format="YY/MM/DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </div>
        </div>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            创建工单
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="批量导入工单"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 字段配置 -->
        <el-tab-pane label="字段配置" name="config">
          <div class="import-config">
            <el-alert
              title="配置说明"
              description="请选择需要导入的字段，系统将根据您的选择生成对应的导入模板。"
              type="info"
              :closable="false"
              style="margin-bottom: 20px"
            />
            
            <h4>基础字段</h4>
            <el-checkbox-group v-model="selectedFields">
              <el-row :gutter="20">
                <el-col :span="8" v-for="field in baseFields" :key="field.key">
                  <el-checkbox :label="field.key" :disabled="field.required">
                    {{ field.label }}
                    <el-tag v-if="field.required" size="small" type="danger">必填</el-tag>
                  </el-checkbox>
                </el-col>
              </el-row>
            </el-checkbox-group>
            
            <h4 v-if="customFields.length > 0" style="margin-top: 20px">自定义字段</h4>
            <el-checkbox-group v-model="selectedCustomFields" v-if="customFields.length > 0">
              <el-row :gutter="20">
                <el-col :span="8" v-for="field in customFields" :key="field.name">
                  <el-checkbox :label="field.name">
                    {{ field.label || field.name }}
                    <el-tag size="small" :type="getFieldTypeColor(field.field_type)">{{ getFieldTypeLabel(field.field_type) }}</el-tag>
                  </el-checkbox>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </div>
        </el-tab-pane>
        
        <!-- 模板下载 -->
        <el-tab-pane label="模板下载" name="template">
          <div class="import-template">
            <el-alert
              title="模板说明"
              type="warning"
              :closable="false"
              style="margin-bottom: 20px"
            >
              <template #default>
                <div>
                  <p><strong>导入格式要求：</strong></p>
                  <ul>
                    <li>文件格式：CSV文件（UTF-8编码）</li>
                    <li>第一行为字段标题，不可修改</li>
                    <li>必填字段不能为空</li>
                    <li>日期格式：YYYY-MM-DD HH:mm:ss</li>
                    <li>选择字段请使用准确的选项值</li>
                  </ul>
                </div>
              </template>
            </el-alert>
            
            <div class="template-preview">
              <h4>模板预览</h4>
              <el-table :data="templatePreview" border style="margin-bottom: 20px">
                <el-table-column
                  v-for="column in templateColumns"
                  :key="column.key"
                  :prop="column.key"
                  :label="column.label"
                  :width="column.width"
                  show-overflow-tooltip
                />
              </el-table>
            </div>
            
            <div class="template-actions">
              <el-button type="primary" @click="downloadTemplate">
                <el-icon><Download /></el-icon>
                下载导入模板
              </el-button>
              <el-button type="primary" @click="downloadSampleData">
                <el-icon><Document /></el-icon>
                下载示例数据
              </el-button>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 文件上传 -->
        <el-tab-pane label="文件上传" name="upload">
          <div class="import-upload">
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              accept=".csv"
              :limit="1"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将CSV文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传CSV文件，且不超过10MB
                </div>
              </template>
            </el-upload>
            
            <div v-if="uploadFile" class="file-info">
              <h4>文件信息</h4>
              <p>文件名：{{ uploadFile.name }}</p>
              <p>文件大小：{{ formatFileSize(uploadFile.size) }}</p>
              <p>预计导入：{{ previewData.length }} 条记录</p>
            </div>
            
            <div v-if="previewData.length > 0" class="data-preview">
              <h4>数据预览（前5条）</h4>
              <el-table :data="previewData.slice(0, 5)" border>
                <el-table-column
                  v-for="column in previewColumns"
                  :key="column.key"
                  :prop="column.key"
                  :label="column.label"
                  show-overflow-tooltip
                />
              </el-table>
            </div>
            
            <div v-if="validationErrors.length > 0" class="validation-errors">
              <h4>数据验证错误</h4>
              <el-alert
                v-for="(error, index) in validationErrors.slice(0, 10)"
                :key="index"
                :title="error"
                type="error"
                :closable="false"
                style="margin-bottom: 5px"
              />
              <p v-if="validationErrors.length > 10" style="color: #f56c6c">
                还有 {{ validationErrors.length - 10 }} 个错误未显示...
              </p>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button v-if="activeTab === 'config'" type="primary" @click="activeTab = 'template'">下一步</el-button>
          <el-button v-if="activeTab === 'template'" @click="activeTab = 'config'">上一步</el-button>
          <el-button v-if="activeTab === 'template'" type="primary" @click="activeTab = 'upload'">下一步</el-button>
          <el-button v-if="activeTab === 'upload'" @click="activeTab = 'template'">上一步</el-button>
          <el-button 
            v-if="activeTab === 'upload'" 
            type="primary" 
            :loading="importLoading"
            :disabled="!uploadFile || validationErrors.length > 0"
            @click="handleImport"
          >
            开始导入
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { workOrdersApi, usersApi, areasApi } from '@/api'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type UploadFile, type UploadInstance } from 'element-plus'
import { Upload, Download, Document, UploadFilled } from '@element-plus/icons-vue'

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

const form = reactive({
  priority: 'medium',
  assignee_id: '',
  area_id: '',
  description: '',
  type: 'maintenance', // 默认为维修
  status: 'pending' // 默认为待接单
})

// 字段相关
const basicFields = ref<any[]>([])
const customFields = ref<any[]>([])
const customFieldValues = reactive<Record<string, any>>({})

// 导入功能相关
const showImportDialog = ref(false)
const activeTab = ref('config')
const importLoading = ref(false)
const uploadRef = ref<UploadInstance>()
const uploadFile = ref<File | null>(null)
const previewData = ref<any[]>([])
const validationErrors = ref<string[]>([])

// 字段配置
const selectedFields = ref<string[]>(['priority', 'area_id'])
const selectedCustomFields = ref<string[]>([])

// 基础字段定义（用于导入功能的备用）
const baseFields = ref([
  { key: 'priority', label: '优先级', required: true, type: 'select', options: ['low', 'medium', 'high', 'urgent'] },
  { key: 'area_id', label: '区域', required: true, type: 'select' },
  { key: 'description', label: '工单描述', required: false, type: 'textarea' },
  { key: 'assignee_id', label: '负责人ID', required: false, type: 'text' },
  { key: 'assignee_name', label: '负责人姓名', required: false, type: 'text' }
])

const rules = {
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
  // 移除area_id的必填验证，只保留工单号和优先级为必填
}

const personnel = ref<any[]>([])
const areas = ref<any[]>([])

// 计算属性
const templateColumns = computed(() => {
  const columns = []
  
  // 添加选中的基础字段
  baseFields.value.forEach(field => {
    if (selectedFields.value.includes(field.key)) {
      columns.push({
        key: field.key,
        label: field.label,
        width: field.key === 'description' ? 200 : 120
      })
    }
  })
  
  // 添加选中的自定义字段
  customFields.value.forEach(field => {
    if (selectedCustomFields.value.includes(field.name)) {
      columns.push({
        key: field.name,
        label: field.label || field.name,
        width: 120
      })
    }
  })
  
  return columns
})

const templatePreview = computed(() => {
  const preview = {}
  templateColumns.value.forEach(column => {
    preview[column.key] = '示例数据'
  })
  return [preview]
})

const previewColumns = computed(() => {
  if (previewData.value.length === 0) return []
  
  const firstRow = previewData.value[0]
  return Object.keys(firstRow).map(key => ({
    key,
    label: getFieldLabel(key)
  }))
})

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 准备自定义字段数据，将field.id转换为field.name
        const customFieldsData: Record<string, any> = {}
        customFields.value.forEach(field => {
          const value = customFieldValues[field.name]
          if (value !== undefined && value !== null && value !== '') {
            customFieldsData[field.name] = value
          }
        })
        
        // 准备工单数据，包含自定义字段
        const workOrderData = {
          ...form,
          custom_fields: customFieldsData
        }
        
        await workOrdersApi.createWorkOrder(workOrderData)
        
        ElMessage.success('工单创建成功')
        router.push('/work-orders')
      } catch (error: any) {
        console.error('创建失败:', error)
        ElMessage.error(error.message || '创建失败')
      } finally {
        loading.value = false
      }
    }
  })
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  // 重置表单字段
  form.priority = 'medium'
  form.assignee_id = ''
  form.area_id = ''
  form.description = ''
  form.type = 'maintenance' // 重置为默认维修
  form.status = 'pending' // 重置为默认待接单
  
  // 重置自定义字段值
  customFields.value.forEach(field => {
    if (field.field_type === 'checkbox') {
          customFieldValues[field.name] = []
        } else {
          customFieldValues[field.name] = ''
        }
  })
}

// 导入功能方法
const getFieldLabel = (key: string) => {
  const baseField = baseFields.value.find(f => f.key === key)
  if (baseField) return baseField.label
  
  const customField = customFields.value.find(f => f.name === key)
  if (customField) return customField.label || customField.name
  
  return key
}

const getFieldTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    'text': 'info',
    'select': 'success',
    'checkbox': 'warning',
    'list': 'primary',
    'datetime': 'danger'
  }
  return colorMap[type] || 'info'
}

const getFieldTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    'text': '文本',
    'select': '单选',
    'checkbox': '多选',
    'list': '列表',
    'datetime': '日期时间'
  }
  return labelMap[type] || type
}

const downloadTemplate = () => {
  const headers = templateColumns.value.map(col => col.label)
  const csvContent = headers.join(',') + '\n'
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', '工单导入模板.csv')
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const downloadSampleData = () => {
  const headers = templateColumns.value.map(col => col.label)
  const sampleRow = templateColumns.value.map(col => {
    switch (col.key) {
      case 'priority': return 'medium'
      case 'assignee_name': return '张三'
      default: return '示例值'
    }
  })
  
  const csvContent = headers.join(',') + '\n' + sampleRow.join(',') + '\n'
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.setAttribute('href', url)
  link.setAttribute('download', '工单导入示例.csv')
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const handleFileChange = (file: UploadFile) => {
  if (!file.raw) return false
  
  uploadFile.value = file.raw
  parseCSVFile(file.raw)
  return false
}

const beforeUpload = (file: File) => {
  const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv')
  if (!isCSV) {
    ElMessage.error('只能上传CSV文件')
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  
  return true
}

const parseCSVFile = (file: File) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const text = e.target?.result as string
    const lines = text.split('\n').filter(line => line.trim())
    
    if (lines.length < 2) {
      ElMessage.error('CSV文件格式错误，至少需要包含表头和一行数据')
      return
    }
    
    const headers = lines[0].split(',')
    const data = []
    
    for (let i = 1; i < lines.length; i++) {
      const values = lines[i].split(',')
      const row: any = {}
      
      headers.forEach((header, index) => {
        row[header.trim()] = values[index]?.trim() || ''
      })
      
      data.push(row)
    }
    
    previewData.value = data
    validateImportData(data)
  }
  
  reader.readAsText(file, 'utf-8')
}

const validateImportData = (data: any[]) => {
  const errors: string[] = []
  
  data.forEach((row, index) => {
    const rowNum = index + 2
    
    baseFields.value.forEach(field => {
      if (field.required && selectedFields.value.includes(field.key)) {
        const fieldLabel = getFieldLabel(field.key)
        if (!row[fieldLabel] || row[fieldLabel].trim() === '') {
          errors.push(`第${rowNum}行：${fieldLabel} 不能为空`)
        }
      }
    })
    
    if (row['优先级'] && !['low', 'medium', 'high', 'urgent'].includes(row['优先级'])) {
      errors.push(`第${rowNum}行：优先级值无效`)
    }
  })
  
  validationErrors.value = errors
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleImport = async () => {
  if (validationErrors.value.length > 0) {
    ElMessage.error('请先修复数据验证错误')
    return
  }
  
  if (previewData.value.length === 0) {
    ElMessage.error('没有可导入的数据')
    return
  }
  
  importLoading.value = true
  
  try {
    let successCount = 0
    let failCount = 0
    
    for (const row of previewData.value) {
      try {
        const workOrderData: any = {
          custom_fields: {}
        }
        
        baseFields.value.forEach(field => {
          if (selectedFields.value.includes(field.key)) {
            const fieldLabel = getFieldLabel(field.key)
            const value = row[fieldLabel]
            
            if (value !== undefined && value !== '') {
              workOrderData[field.key] = value
            }
          }
        })
        
        customFields.value.forEach(field => {
          if (selectedCustomFields.value.includes(field.name)) {
            const fieldLabel = getFieldLabel(field.name)
            const value = row[fieldLabel]
            
            if (value !== undefined && value !== '') {
              workOrderData.custom_fields[field.name] = value
            }
          }
        })
        
        await workOrdersApi.createWorkOrder(workOrderData)
        successCount++
      } catch (error) {
        console.error('创建工单失败:', error)
        failCount++
      }
    }
    
    ElMessage.success(`导入完成！成功创建 ${successCount} 个工单${failCount > 0 ? `，失败 ${failCount} 个` : ''}`)
    showImportDialog.value = false
    
  } catch (error) {
    console.error('批量导入失败:', error)
    ElMessage.error('批量导入失败，请重试')
  } finally {
    importLoading.value = false
  }
}

const loadPersonnel = async () => {
  try {
    // 获取用户列表
    const response = await usersApi.getUsers({ page: 1, per_page: 100 })
    personnel.value = response.data.users || response.data || []
  } catch (error) {
    console.error('加载人员列表失败:', error)
    ElMessage.error('加载人员列表失败')
  }
}

const loadAreas = async () => {
  try {
    const response = await areasApi.getAreaOptions()
    areas.value = response.data || []
  } catch (error) {
    console.error('加载区域列表失败:', error)
    ElMessage.error('加载区域列表失败')
  }
}

const loadBasicFields = async () => {
  try {
    const response = await workOrdersApi.getFields({ field_category: 'basic' })
    if (response.data.fields && response.data.fields.length > 0) {
      basicFields.value = response.data.fields.filter(field => field.is_active)
      // 按sort_order排序
      basicFields.value.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0))
      
      // 初始化基础字段值
      basicFields.value.forEach(field => {
        if (field.default_value) {
          form[field.name] = field.default_value
        }
        // 设置特定字段的默认值
        if (field.name === 'type') {
          form[field.name] = 'maintenance' // 工单类型默认为维修
        } else if (field.name === 'status') {
          form[field.name] = 'pending' // 工单状态默认为待接单
        }
      })
      
      // 动态生成表单验证规则
      generateFormRules()
    }
  } catch (error) {
    console.error('加载基础字段失败:', error)
    ElMessage.error('加载基础字段失败')
  }
}

const loadCustomFields = async () => {
  try {
    const response = await workOrdersApi.getFields({ field_category: 'custom' })
    customFields.value = response.data.fields?.filter(field => field.is_active) || []
    // 按sort_order排序
    customFields.value.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0))
    
    // 初始化自定义字段值
    customFields.value.forEach(field => {
      if (field.field_type === 'checkbox') {
        customFieldValues[field.name] = []
      } else {
        customFieldValues[field.name] = field.default_value || ''
      }
    })
  } catch (error) {
    console.error('加载自定义字段失败:', error)
    ElMessage.error('加载自定义字段失败')
  }
}

// 计算属性：可见的基础字段
const visibleBasicFields = computed(() => {
  return basicFields.value.filter(field => field.is_visible !== false)
})

// 动态生成表单验证规则
const generateFormRules = () => {
  const newRules: any = {}
  
  basicFields.value.forEach(field => {
    // 只有工单号和优先级为必填项
    if (field.name === 'work_order_number' || field.name === 'priority') {
      const fieldType = field.field_type
      const trigger = fieldType === 'select' ? 'change' : 'blur'
      const message = fieldType === 'select' ? `请选择${field.label}` : `请输入${field.label}`
      
      newRules[field.name] = [
        { required: true, message, trigger }
      ]
    }
  })
  
  // 合并到现有规则
  Object.assign(rules, newRules)
}

// 获取字段选项
const getFieldOptions = (field: any) => {
  if (field.name === 'priority') {
    // 优先级字段的选项映射
    const priorityMap = {
      'low': '低',
      'medium': '中', 
      'high': '高',
      'urgent': '紧急'
    }
    return Object.entries(priorityMap).map(([value, label]) => ({ value, label }))
  } else if (field.name === 'type') {
    // 工单类型字段的中文选项
    const typeMap = {
      'maintenance': '维修',
      'installation': '安装',
      'inspection': '巡检',
      'repair': '抢修',
      'other': '其他'
    }
    return Object.entries(typeMap).map(([value, label]) => ({ value, label }))
  } else if (field.name === 'status') {
    // 工单状态字段的中文选项
    const statusMap = {
      'pending': '待接单',
      'in_progress': '进行中',
      'completed': '已完成',
      'cancelled': '已取消'
    }
    return Object.entries(statusMap).map(([value, label]) => ({ value, label }))
  } else if (field.name === 'assignee_id') {
    // 负责人字段
    return personnel.value.map(person => ({ value: person.id, label: person.name }))
  } else if (field.name === 'area_id') {
    // 区域字段
    return areas.value
  } else if (field.options) {
    // 其他有选项的字段
    try {
      const options = typeof field.options === 'string' ? JSON.parse(field.options) : field.options
      return Array.isArray(options) ? options.map(opt => ({ value: opt, label: opt })) : []
    } catch {
      return []
    }
  }
  return []
 }

 // 获取自定义字段选项
 const getCustomFieldOptions = (field: any) => {
   if (field.options) {
     try {
       const options = typeof field.options === 'string' ? JSON.parse(field.options) : field.options
       return Array.isArray(options) ? options.map(opt => ({ value: opt, label: opt })) : []
     } catch {
       return []
     }
   }
   return []
 }
 
 onMounted(() => {
  loadPersonnel()
  loadAreas()
  loadBasicFields()
  loadCustomFields()
})

// 导入对话框控制
const openImportDialog = () => {
  showImportDialog.value = true
  activeTab.value = 'config'
}

const closeImportDialog = () => {
  showImportDialog.value = false
  uploadFile.value = null
  previewData.value = []
  validationErrors.value = []
  activeTab.value = 'config'
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}
</script>

<style scoped>
.work-order-create {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}
</style>
